//
//  PossesionStore.m
//  Homepwner
//
//  Created by jiayi xiao on 12-4-20.
//  Copyright 2012年 nju. All rights reserved.
//

#import "PossesionStore.h"
#import "Possession.h"
#import "ImageStore.h"
 
static PossesionStore *defaultStore=nil;
@implementation PossesionStore

+(PossesionStore *) defaultStore
{
    if(!defaultStore)
    {
        defaultStore=[[super allocWithZone:NULL]init];
    }
    return defaultStore;
}

+(id) allocWithZone:(NSZone *)zone
{
    return [self defaultStore];
}

- (id)init
{
    if(defaultStore)
    {
        return defaultStore;
    }
    self=[super init];
//    if(self)
//    {
//        allPossesions=[[NSMutableArray alloc]init];
//    }
    return self;
}

-(id)retain
{
    return  self;
}

-(void) release
{
    
}

-(NSUInteger) retainCount
{
    return NSUIntegerMax;
}

-(NSArray *)allPossesions
{
    [self fetchPossessionIfNecessary];
    return allPossesions;
}

-(Possession *)createPossesion
{
    [self fetchPossessionIfNecessary];
    Possession *p=[Possession randomPossession];
    [allPossesions addObject:p];
    return p;
}

-(void) removePossession:(Possession *)p
{
    NSString *key=[p imageKey];
    [[ImageStore defaultImageStore] deleteImageForKey:key];
    [allPossesions removeObjectIdenticalTo:p];
}

-(void) movePossessionAtIndex:(int) from toIndex:(int) to
{
    if(from==to)
    {
        return;
    }
    Possession *p=[allPossesions objectAtIndex:from];
    [p retain];
    [allPossesions removeObjectAtIndex:from];
    [allPossesions insertObject:p atIndex:to];
    [p release];
}

-(NSString *)possessionArchivePath
{
    return pathInDocumentDirectory(@"possessions.data");
}

-(BOOL) saveChanges
{
    return [NSKeyedArchiver archiveRootObject:allPossesions toFile:[self possessionArchivePath]];
}

-(void) fetchPossessionIfNecessary
{
    if(!allPossesions)
    {
        NSString *path=[self possessionArchivePath];
        allPossesions=[[NSKeyedUnarchiver unarchiveObjectWithFile:path]retain];
    }
    if(!allPossesions)
    {
        allPossesions=[[NSMutableArray alloc]init];
    }
}

@end
